package controller

import (
	"errors"
	"fmt"
	"log"
	"net/http"
	"strings"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/service"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/auth"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/communication"

	"github.com/gin-gonic/gin"
)

// AuthController 认证控制器
type AuthController struct {
	userService *service.UserService
	emailUtil   *communication.EmailUtil
	smsUtil     *communication.SmsUtil
	gaUtil      *auth.GAUtil
}

// NewAuthController 创建认证控制器实例
func NewAuthController() (*AuthController, error) {
	userService := service.NewUserService()
	emailUtil, err := communication.NewEmailUtil()
	if err != nil {
		return nil, fmt.Errorf("创建邮件工具失败: %v", err)
	}
	smsUtil, err := communication.NewSmsUtil()
	if err != nil {
		return nil, fmt.Errorf("创建短信工具失败: %v", err)
	}
	gaUtil := auth.NewGAUtil()

	return &AuthController{
		userService: userService,
		emailUtil:   emailUtil,
		smsUtil:     smsUtil,
		gaUtil:      gaUtil,
	}, nil
}

// PreLogin 预登录
func (ac *AuthController) PreLogin(ctx *gin.Context) {
	var req struct {
		LoginId  string `json:"loginId" binding:"required"`
		Password string `json:"password" binding:"required"`
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 只查 password 和 id
	var user struct {
		ID       int64
		Password string
	}
	err := ac.userService.DB().Model(&models.User{}).
		Select("id, password").
		Where("username = ? OR email = ? OR phone = ?", req.LoginId, req.LoginId, req.LoginId).
		First(&user).Error
	if err != nil {
		common.Error(ctx, http.StatusUnauthorized, "user_not_found", err)
		return
	}
	if !ac.userService.ValidatePasswordRaw(user.Password, req.Password) {
		common.Error(ctx, http.StatusUnauthorized, "invalid_credentials", nil)
		return
	}

	// 获取完整的用户信息
	fullUser, err := ac.userService.GetUserByID(user.ID)
	if err != nil {
		common.Error(ctx, http.StatusUnauthorized, "user_not_found", err)
		return
	}

	// 获取用户的矩阵账户信息
	var matrixAccount struct {
		MatrixAccount string
		Status        string
		PlatformType  string
	}
	err = ac.userService.DB().Table("user_matrix_accounts").
		Select("matrix_account, status, platform_type").
		Where("user_id = ? AND status = 'active'", user.ID).
		First(&matrixAccount).Error

	// 从user_roles表获取role_id
	var userRole struct {
		RoleID int64
	}
	err = ac.userService.DB().Table("user_roles").
		Select("role_id").
		Where("user_id = ?", user.ID).
		First(&userRole).Error
	if err != nil {
		log.Printf("获取用户角色失败: %v", err)
	}

	// 获取用户的认证方式
	authMethods, err := ac.userService.GetUserAuthMethods(user.ID)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_auth_methods_failed", err)
		return
	}

	// 检查是否有启用的认证方式
	var enabledAuthMethods []string
	for _, method := range authMethods {
		if method.IsEnabled == 1 {
			enabledAuthMethods = append(enabledAuthMethods, method.AuthType)
		}
	}

	// 生成预登录令牌
	preLoginToken, err := auth.GeneratePreLoginToken(user.ID, fullUser.Username)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "generate_token_failed", err)
		return
	}

	// 如果有启用的认证方式，返回预登录令牌和认证方式列表
	if len(enabledAuthMethods) > 0 {
		common.Success(ctx, gin.H{
			"preLoginToken": preLoginToken,
			"authMethods":   enabledAuthMethods,
			"message":       "verification_required",
			"user": gin.H{
				"id":              fullUser.ID,
				"username":        fullUser.Username,
				"email":           fullUser.Email,
				"phone":           fullUser.Phone,
				"name":            fullUser.Name,
				"status":          fullUser.Status,
				"last_login_time": fullUser.LastLoginTime,
				"last_login_ip":   fullUser.LastLoginIP,
				"created_at":      fullUser.CreatedAt,
				"updated_at":      fullUser.UpdatedAt,
				"invitation_code": fullUser.InvitationCode,
				"role_id":         userRole.RoleID,
				"is_deleted":      fullUser.IsDeleted,
				"platform_type":   matrixAccount.PlatformType,
			},
		})
		return
	}

	// 如果没有启用的认证方式，直接生成正式登录令牌
	token, err := auth.GenerateToken(fullUser.ID, fullUser.Username, userRole.RoleID)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "generate_token_failed", err)
		return
	}

	// 检查是否为异常登录
	isUnusual := ac.checkUnusualLogin(ctx, fullUser)

	// 记录登录
	if err := ac.recordLogin(ctx, fullUser, isUnusual); err != nil {
		log.Printf("记录登录失败: %v", err)
	}

	common.Success(ctx, gin.H{
		"token": token,
		"user": gin.H{
			"id":              fullUser.ID,
			"username":        fullUser.Username,
			"email":           fullUser.Email,
			"phone":           fullUser.Phone,
			"name":            fullUser.Name,
			"status":          fullUser.Status,
			"last_login_time": fullUser.LastLoginTime,
			"last_login_ip":   fullUser.LastLoginIP,
			"created_at":      fullUser.CreatedAt,
			"updated_at":      fullUser.UpdatedAt,
			"invitation_code": fullUser.InvitationCode,
			"role_id":         userRole.RoleID,
			"is_deleted":      fullUser.IsDeleted,
			"platform_type":   matrixAccount.PlatformType,
		},
	})
}

// getParentMatrixAccount 获取父级矩阵账户
func (ac *AuthController) getParentMatrixAccount(matrixAccount string) (string, error) {
	var matrixAccountInfo struct {
		MatrixAccount       string
		ParentMatrixAccount string
	}

	// 查询当前矩阵账户信息
	err := ac.userService.DB().Table("user_matrix_accounts").
		Select("uma.matrix_account, parent.matrix_account as parent_matrix_account").
		Joins("LEFT JOIN user_matrix_accounts parent ON uma.parent_matrix_account_id = parent.id").
		Where("uma.matrix_account = ?", matrixAccount).
		Scan(&matrixAccountInfo).Error

	if err != nil {
		return "", err
	}

	// 如果找到父级账户，返回父级账户号
	if matrixAccountInfo.ParentMatrixAccount != "" {
		return matrixAccountInfo.ParentMatrixAccount, nil
	}

	return matrixAccount, nil
}

// VerifyAndLogin 验证并登录
func (ac *AuthController) VerifyAndLogin(ctx *gin.Context) {
	var req struct {
		PreLoginToken string `json:"pre_login_token" binding:"required"`
		AuthMethod    string `json:"auth_method" binding:"required"`
		Code          string `json:"code" binding:"required"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 验证预登录令牌
	claims, err := auth.ValidatePreLoginToken(req.PreLoginToken)
	if err != nil {
		common.Error(ctx, http.StatusUnauthorized, "invalid_token", err)
		return
	}

	// 获取用户信息
	user, err := ac.userService.GetUserByID(int64(claims.UserID))
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "error", err)
		return
	}

	// 从user_roles表获取role_id
	var userRole struct {
		RoleID int64
	}
	err = ac.userService.DB().Table("user_roles").
		Select("role_id").
		Where("user_id = ?", user.ID).
		First(&userRole).Error
	if err != nil {
		log.Printf("获取用户角色失败: %v", err)
	}

	// 获取用户的矩阵账户信息
	var matrixAccount struct {
		MatrixAccount string
		Status        string
		PlatformType  string
	}
	err = ac.userService.DB().Table("user_matrix_accounts").
		Select("matrix_account, status, platform_type").
		Where("user_id = ? AND status = 'active'", user.ID).
		First(&matrixAccount).Error

	// 处理矩阵账户信息
	var effectiveMatrixAccount string
	if err == nil {
		// 如果矩阵账户以SUB开头，获取其父级账户
		if strings.HasPrefix(matrixAccount.MatrixAccount, "SUB") {
			parentAccount, err := ac.getParentMatrixAccount(matrixAccount.MatrixAccount)
			if err != nil {
				log.Printf("获取父级矩阵账户失败: %v", err)
			} else {
				effectiveMatrixAccount = parentAccount
			}
		} else {
			effectiveMatrixAccount = matrixAccount.MatrixAccount
		}
	}

	// 验证用户的认证方式设置
	authMethods, err := ac.userService.GetUserAuthMethods(int64(user.ID))
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_auth_methods_failed", err)
		return
	}

	// 验证认证方式
	var authMethod *models.UserAuthMethod
	for _, method := range authMethods {
		if method.AuthType == req.AuthMethod {
			authMethod = &method
			break
		}
	}

	if authMethod == nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_auth_method", nil)
		return
	}

	// 根据认证方式验证验证码
	var isValid bool
	switch req.AuthMethod {
	case "email":
		isValid, err = ac.emailUtil.VerifyCode(user.Email, req.Code, "login")
	case "sms":
		isValid, err = ac.smsUtil.VerifyCode(user.Phone, req.Code, "login")
	case "ga":
		// 验证谷歌验证器
		isValid = ac.gaUtil.VerifyToken(authMethod.AuthSecret, req.Code)
		err = nil
	default:
		common.Error(ctx, http.StatusBadRequest, "unsupported_auth_method", nil)
		return
	}

	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "verify_code_failed", err)
		return
	}

	if !isValid {
		common.Error(ctx, http.StatusUnauthorized, "invalid_code", nil)
		return
	}

	// 创建正式登录令牌
	token, err := auth.GenerateToken(int64(user.ID), user.Username, userRole.RoleID)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "error", err)
		return
	}

	// 检查是否为异常登录
	isUnusual := ac.checkUnusualLogin(ctx, user)

	// 记录登录
	if err := ac.recordLogin(ctx, user, isUnusual); err != nil {
		log.Printf("记录登录失败: %v", err)
	}

	common.Success(ctx, gin.H{
		"token": token,
		"user": gin.H{
			"id":              user.ID,
			"username":        user.Username,
			"email":           user.Email,
			"phone":           user.Phone,
			"name":            user.Name,
			"status":          user.Status,
			"last_login_time": user.LastLoginTime,
			"last_login_ip":   user.LastLoginIP,
			"created_at":      user.CreatedAt,
			"updated_at":      user.UpdatedAt,
			"invitation_code": user.InvitationCode,
			"role_id":         userRole.RoleID,
			"is_deleted":      user.IsDeleted,
			"matrix_account":  effectiveMatrixAccount,
			"platform_type":   matrixAccount.PlatformType,
		},
	})
}

// SendLoginVerificationCode 发送登录验证码
func (ac *AuthController) SendLoginVerificationCode(ctx *gin.Context) {
	var req struct {
		PreLoginToken string `json:"preLoginToken" binding:"required"`
		Method        string `json:"method" binding:"required"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 验证预登录令牌
	claims, err := auth.ValidatePreLoginToken(req.PreLoginToken)
	if err != nil {
		switch {
		case errors.Is(err, auth.ErrExpiredToken):
			common.Error(ctx, http.StatusUnauthorized, "pre_login_token_expired", nil)
		case strings.Contains(err.Error(), "empty or undefined"):
			common.Error(ctx, http.StatusBadRequest, "pre_login_token_required", nil)
		case strings.Contains(err.Error(), "malformed"):
			common.Error(ctx, http.StatusBadRequest, "pre_login_token_invalid", err)
		default:
			common.Error(ctx, http.StatusUnauthorized, "pre_login_token_invalid", err)
		}
		return
	}

	// 获取用户信息
	user, err := ac.userService.FindByID(claims.UserID)
	if err != nil {
		common.Error(ctx, http.StatusNotFound, "user_not_found", err)
		return
	}

	// 验证用户的认证方式设置
	authMethods, err := ac.userService.GetUserAuthMethods(int64(user.ID))
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_auth_methods_failed", err)
		return
	}

	// 验证用户是否启用了所选验证方式
	var authMethod *models.UserAuthMethod
	for _, method := range authMethods {
		if method.AuthType == req.Method && method.IsEnabled == 1 {
			authMethod = &method
			break
		}
	}

	if authMethod == nil {
		common.Error(ctx, http.StatusForbidden, "auth_method_not_enabled", nil)
		return
	}

	// 根据所选验证方式发送验证码
	switch req.Method {
	case "email":
		if err := ac.emailUtil.SendLoginCode(user.Email); err != nil {
			common.Error(ctx, http.StatusInternalServerError, "verification_code_send_failed", err)
			return
		}
		common.Success(ctx, gin.H{
			"message": "verification_code_sent",
			"email":   maskEmail(user.Email),
		})

	case "sms":
		if err := ac.smsUtil.SendVerificationCode(user.Phone, "login"); err != nil {
			common.Error(ctx, http.StatusInternalServerError, "verification_code_send_failed", err)
			return
		}
		common.Success(ctx, gin.H{
			"message": "verification_code_sent",
			"phone":   maskPhone(user.Phone),
		})

	case "ga":
		common.Success(ctx, gin.H{
			"message": "verification_required",
		})

	default:
		common.Error(ctx, http.StatusBadRequest, "verification_method_required", nil)
	}
}

// GetGoogleAuthenticatorQRCode 获取谷歌验证器二维码
func (ac *AuthController) GetGoogleAuthenticatorQRCode(ctx *gin.Context) {
	// 获取当前用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	// 检查是否已绑定谷歌验证器
	exists, err := ac.userService.CheckAuthMethodExists(userID.(int64), "ga")
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "check_ga_status_failed", err)
		return
	}
	if exists {
		common.Error(ctx, http.StatusBadRequest, "ga_already_bound", nil)
		return
	}

	// 获取谷歌验证器二维码
	qrCode, secret, err := ac.userService.GetGoogleAuthenticatorQRCode(userID.(int64))
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_ga_qrcode_failed", err)
		return
	}

	// 将密钥临时存储到Redis中，设置5分钟过期时间
	key := fmt.Sprintf("ga_binding_secret:%d", userID.(int64))
	if err := database.SetWithExpiration(ctx, key, secret, 5*time.Minute); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "store_secret_failed", err)
		return
	}

	common.Success(ctx, gin.H{
		"qr_code": qrCode,
		"secret":  secret,
	})
}

// BindGoogleAuthenticator 绑定谷歌验证器
func (ac *AuthController) BindGoogleAuthenticator(ctx *gin.Context) {
	// 获取当前用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	// 获取请求参数
	var req struct {
		Code string `json:"code" binding:"required"`
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_request", err)
		return
	}

	// 从Redis获取临时存储的密钥
	key := fmt.Sprintf("ga_binding_secret:%d", userID.(int64))
	secret, err := database.Get(ctx, key)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "secret_expired_or_not_found", err)
		return
	}

	// 绑定谷歌验证器
	err = ac.userService.BindGoogleAuthenticator(userID.(int64), req.Code, secret)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "bind_ga_failed", err)
		return
	}

	// 删除临时存储的密钥
	database.Delete(ctx, key)

	common.Success(ctx, gin.H{
		"message": "谷歌验证器绑定成功",
	})
}

// UnbindGoogleAuthenticator 解绑谷歌验证器
func (ac *AuthController) UnbindGoogleAuthenticator(ctx *gin.Context) {
	// 获取当前用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	// 验证请求参数
	var req struct {
		Code string `json:"code" binding:"required"`
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 验证谷歌验证器
	valid, err := ac.userService.VerifyGoogleAuthenticator(userID.(int64), req.Code)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "verify_ga_failed", err)
		return
	}
	if !valid {
		common.Error(ctx, http.StatusUnauthorized, "invalid_code", nil)
		return
	}

	// 解绑谷歌验证器
	if err := ac.userService.UnbindGoogleAuthenticator(userID.(int64)); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "unbind_ga_failed", err)
		return
	}

	common.Success(ctx, gin.H{
		"message": "ga_unbound",
	})
}

// VerifyGoogleAuthenticator 验证谷歌验证器
func (ac *AuthController) VerifyGoogleAuthenticator(ctx *gin.Context) {
	// 获取当前用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	// 验证请求参数
	var req struct {
		Code string `json:"code" binding:"required"`
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 验证谷歌验证器
	valid, err := ac.userService.VerifyGoogleAuthenticator(userID.(int64), req.Code)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "verify_ga_failed", err)
		return
	}
	if !valid {
		common.Error(ctx, http.StatusUnauthorized, "invalid_code", nil)
		return
	}

	common.Success(ctx, gin.H{
		"message": "verification_success",
	})
}

// SendRegisterVerificationCode 发送注册验证码
func (ac *AuthController) SendRegisterVerificationCode(ctx *gin.Context) {
	var req struct {
		Email string `json:"email" binding:"required,email"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 检查邮箱是否已被注册
	_, err := ac.userService.FindByLoginID(req.Email)
	if err == nil {
		common.Error(ctx, http.StatusBadRequest, "email_already_exists", nil)
		return
	}

	// 发送注册验证码
	if err := ac.emailUtil.SendRegisterCode(req.Email); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "verification_code_send_failed", err)
		return
	}

	common.Success(ctx, gin.H{
		"message": "verification_code_sent",
		"email":   maskEmail(req.Email),
	})
}

// Register 用户注册
func (ac *AuthController) Register(ctx *gin.Context) {
	var req struct {
		Username         string `json:"username" binding:"required,min=3,max=50"`
		Password         string `json:"password" binding:"required,min=6,max=20"`
		Email            string `json:"email" binding:"required,email,max=100"`
		Phone            string `json:"phone" binding:"required,len=11"`
		Name             string `json:"name" binding:"max=50"`
		VerificationCode string `json:"verification_code" binding:"required"`
		InvitationCode   string `json:"invitation_code"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 验证注册验证码
	valid, err := ac.emailUtil.VerifyRegisterCode(req.Email, req.VerificationCode)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "verify_code_failed", err)
		return
	}
	if !valid {
		common.Error(ctx, http.StatusUnauthorized, "invalid_code", nil)
		return
	}

	// 注册用户
	user, err := ac.userService.Register(
		req.Username,
		req.Password,
		req.Email,
		req.Phone,
		req.Name,
		req.InvitationCode,
	)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "user_register_failed", err)
		return
	}

	common.Success(ctx, gin.H{
		"message": "user_register_success",
		"data":    user,
	})
}

// 辅助函数

// maskEmail 隐藏邮箱中间部分
func maskEmail(email string) string {
	parts := strings.Split(email, "@")
	if len(parts) != 2 {
		return email
	}
	username := parts[0]
	if len(username) <= 3 {
		return email
	}
	return username[:3] + "***@" + parts[1]
}

// maskPhone 隐藏手机号中间部分
func maskPhone(phone string) string {
	if len(phone) != 11 {
		return phone
	}
	return phone[:3] + "****" + phone[7:]
}

// recordLogin 记录登录
func (ac *AuthController) recordLogin(ctx *gin.Context, user *models.User, isUnusual bool) error {
	now := time.Now()
	ip := ctx.ClientIP()
	userAgent := ctx.GetHeader("User-Agent")

	// 更新用户最后登录时间和IP
	user.LastLoginTime = now
	user.LastLoginIP = ip
	if err := ac.userService.Update(user); err != nil {
		return fmt.Errorf("更新用户登录信息失败: %v", err)
	}

	// 创建登录记录
	record := &models.UserLoginRecord{
		UserID:    int64(user.ID),
		IP:        ip,
		LoginTime: now,
		UserAgent: userAgent,
		IsUnusual: int8(boolToInt(isUnusual)),
	}

	// 获取IP地理位置信息
	ipInfo, err := common.GetIPInfo(ip)
	if err != nil {
		// 如果获取IP信息失败，仍然记录登录，但位置信息为未知
		record := &models.UserLoginRecord{
			UserID:    int64(user.ID),
			IP:        ip,
			LoginTime: now,
			UserAgent: userAgent,
			Location:  "未知",
			IsUnusual: int8(boolToInt(isUnusual)),
		}

		// 如果是异常登录，发送邮件通知
		if isUnusual {
			go ac.sendUnusualLoginEmail(user, ip, "未知", now, userAgent)
		}

		return ac.userService.CreateLoginRecord(record)
	}

	// 设置位置信息
	location := fmt.Sprintf("%s %s", ipInfo.Country, ipInfo.City)
	record.Location = location

	// 如果是异常登录，发送邮件通知
	if isUnusual {
		go ac.sendUnusualLoginEmail(user, ip, location, now, userAgent)
	}

	return ac.userService.CreateLoginRecord(record)
}

// sendUnusualLoginEmail 发送异常登录邮件通知
func (ac *AuthController) sendUnusualLoginEmail(user *models.User, ip, location string, loginTime time.Time, userAgent string) {
	// 构建登录信息
	loginInfo := struct {
		IP       string
		Location string
		Time     time.Time
		Device   string
	}{
		IP:       ip,
		Location: location,
		Time:     loginTime,
		Device:   userAgent,
	}

	// 发送异常登录提醒邮件
	if err := ac.emailUtil.SendUnusualLoginAlert(user.Email, loginInfo); err != nil {
		log.Printf("发送异常登录邮件通知失败 - 用户ID: %d, 邮箱: %s, 错误: %v", user.ID, user.Email, err)
	} else {
		log.Printf("已发送异常登录邮件通知 - 用户ID: %d, 邮箱: %s, IP: %s, 位置: %s", user.ID, user.Email, ip, location)
	}
}

// boolToInt 将布尔值转换为整数
func boolToInt(b bool) int {
	if b {
		return 1
	}
	return 0
}

// checkUnusualLogin 检查是否是不寻常的登录
func (ac *AuthController) checkUnusualLogin(ctx *gin.Context, user *models.User) bool {
	ip := ctx.ClientIP()
	userAgent := ctx.GetHeader("User-Agent")

	// 查询用户最近的登录记录
	lastLogin, err := ac.userService.GetLastLoginRecord(int64(user.ID))
	if err != nil {
		return false
	}

	// 如果没有登录记录，视为正常登录
	if lastLogin == nil {
		return false
	}

	// 检查IP是否变化
	if lastLogin.IP != ip {
		return true
	}

	// 检查User-Agent是否变化
	if lastLogin.UserAgent != userAgent {
		return true
	}

	return false
}
